import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

public class ServerThread extends Thread {

	private ServerSocket serverSocket;
	private int port;
	private static ServerThread instance = null;
	private static Object lock = new Object();

	// Singleton Pattern
	public static ServerThread instance() {
		if (instance == null) {
			// Double check locking
			synchronized (lock) {
				if (instance == null) {
					instance = new ServerThread();
				}
			}
		}
		return instance;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public void run() {
		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			Module.writeToScreen("Could not listen on port: " + port);
			System.exit(-1);
		}

		while (true) {
			ClientWorker clientWorker;
			try {
				Module.writeToScreen("Ready for new connections");
				// server.accept returns a client connection
				clientWorker = new ClientWorker(serverSocket.accept());
				Module.writeToScreen("Client connected");
				clientWorker.start();
				// New receiving thread started to receive the file.
			} catch (IOException e) {
				Module.writeToScreen("Accept failed: " + port);
				System.exit(-1);
			}
		}
	}
}
